<template>
	<uni-list>
		<uni-list-item showArrow @tap="onAvatarTap" link>
			<template v-slot:header>
				<view class="d-flex a-center j-center">头像</view>
			</template>
			<template v-slot:footer>
				<image class="slot-image rounded" :src="user.avatar" style="height: 80rpx;width: 80rpx;"
					mode="widthFix"></image>
			</template>
		</uni-list-item>
		<uni-list-item @tap="onUsernameTap" showArrow title="用户名" :rightText="user.username" link>
		</uni-list-item>
	</uni-list>
	<view>
		<!-- 输入框示例 -->
		<uni-popup ref="dialog" type="dialog">
			<uni-popup-dialog ref="input" mode="input" title="修改用户名" value="原来的用户名!" placeholder="请输入内容"
				@confirm="onUsernameConfirm"></uni-popup-dialog>
		</uni-popup>
	</view>
</template>

<script setup>
defineOptions({
	name: 'UserInfo',
})
import { ref } from 'vue'
const dialog = ref()
const input = ref()
import userHttp from '@/apis/user/userHttp.js'
import useAuthStore from '@/stores/auth.js'
const authStore = useAuthStore()

const user=ref({
	username:authStore.user.username,
	avatar:authStore.user.avatar,
})

const onAvatarTap = () => {
	uni.chooseImage({
		count: 1,
		extension: ['.jpg', '.jpeg', '.png', '.gif', '.webp'],
		success: async (chooseImagesRes) => {
			const tempFilePaths=chooseImagesRes.tempFilePaths;
			uni.showLoading({
				title: '上传中'
			})
			await userHttp.updateAccessToken()
			// 上传到服务器
			uni.uploadFile({
				url: import.meta.env.VITE_BASE_USER_URL + '/user/update/avatar',
				header:{
					'Authorization': 'Bearer ' + authStore.access_token
				},
				filePath: tempFilePaths[0],
				name: 'file',
				success: (uploadFileRes) => {
					if (uploadFileRes.statusCode==200) {
						uni.showToast({
							title: '上传成功',
							icon: 'success'
						})
					}
					const result=JSON.parse(uploadFileRes.data)
					authStore.user.avatar=result.avatar;
					uni.hideLoading()
				},
				fail: (uploadFileRes) => {
					uni.hideLoading()
					uni.showToast({
						title: '上传失败',
						icon: 'error'
					})
				}
			})
			
		}
	})
}
const onUsernameTap = () => {
	dialog.value.open()
}
const onUsernameConfirm = async (value) => {
	const reuslt=await userHttp.updateUsername(value)
	if (reuslt) {
		uni.showToast({
			title: '修改成功',
			icon: 'success'
		})
		let tmp=authStore.user;
		tmp.username=value;
		authStore.setUser(tmp)
	}
}


</script>

<style></style>
